import $c from '@/common/config.js';
export default {
	config: {
		baseUrl: $c.baseUrl,
		headers: {},
		dataType: "json",
		responseType: "text"
	},
	interceptor: {
		request: null,
		response: null
	},
	request(options) {
		return new Promise((resolve, reject) => {
			let _config = null
			options.url = this.config.baseUrl + options.url
			options.complete = (response) => {
				let statusCode = response.statusCode
				response.config = _config
				if (process.env.NODE_ENV === 'development') {
					if (statusCode === 200) {
						// console.log("【" + _config.requestId + "】 结果：" + JSON.stringify(response.data))
					}
				}
				if (this.interceptor.response) {
					let newResponse = this.interceptor.response(response)
					if (newResponse) {
						response = newResponse
					}
				}
				if (statusCode === 200) {
					if (response.data.code + '' !== '200') { //成功
						uni.showToast({
							title: response.data.msg,
							icon: 'none'
						})
					}
					resolve(response.data);
				} else {
					reject(response.data)
				}

			}
			_config = Object.assign({}, this.config, options)
			_config.requestId = new Date().getTime()
			if (this.interceptor.request) {
				this.interceptor.request(_config)
			}
			if (process.env.NODE_ENV === 'development') {
				// console.log("【" + _config.requestId + "】 地址：" + _config.url)
				if (_config.data) {
					// console.log("【" + _config.requestId + "】 参数：" + JSON.stringify(_config.data))
				}
			}
			uni.request(_config);
		});
	},
	get(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'GET'
		return this.request(options)
	},
	post(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'POST'
		return this.request(options)
	},
	put(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'PUT'
		return this.request(options)
	},
	delete(url, data, options) {
		if (!options) {
			options = {}
		}
		options.url = url
		options.data = data
		options.method = 'DELETE'
		return this.request(options)
	},
	// 上传文件
	upload(url, data, dataName = 'file', onProgress = false) {
		return new Promise((resolve, reject) => {
			const uploadTask = uni.uploadFile({
				url: $c.baseUrl + url,
				filePath: data,
				name: dataName,
				success: (uploadRes) => {
					let uploadFile = {
						data: {}
					}
					uploadRes = JSON.parse(uploadRes.data);
					uploadFile.data.code = uploadRes.code
					if (uploadRes.code != 200) {
						uploadFile.data.msg = uploadRes.msg
						resolve(uploadFile)
					} else {
						uploadFile.data.data = uploadRes.data.url
						resolve(uploadFile)
					}
				},
				fail: (err) => {
					reject(err)
				}
			})
			// #ifndef MP-ALIPAY
			uploadTask.onProgressUpdate((res) => {
				if (typeof onProgress === 'function') {
					onProgress(res.progress)
				}
			});
			// #endif
		})
	}
}